//
//  LWHeaderView.m
//  LWShopItem
//
//  Created by mac on 17/3/17.
//  Copyright © 2017年 LWShop.com. All rights reserved.
//

#import "LWHeaderView.h"
#import <Masonry.h>
#import "LWLogInVc.h"
#import "AppDelegate.h"

@interface LWHeaderView ()

@property (strong, nonatomic) UIButton *nickname; // 昵称
@property (strong, nonatomic) UIImageView *imageView; // 用户头像



@end

@implementation LWHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        [self setupUI];
    }
    return self;
}

#pragma mark - UI
- (void)setupUI
{
    self.backgroundColor = [UIColor orangeColor];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"BG1"]];
    
    imageView.frame = CGRectMake(0, 0, self.frame.size.width, 160);
    
    
    [self addSubview:imageView];
    
    UIButton *logInBtn = [UIButton new];
    [logInBtn setTitle:[[NSUserDefaults standardUserDefaults] valueForKey:@"token"] ? [[NSUserDefaults standardUserDefaults] valueForKey:@"nickname"] : @"请登录" forState:UIControlStateNormal];
    [logInBtn addTarget:self action:@selector(logInBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:logInBtn];
    [logInBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self);
        make.centerY.equalTo(self);
    }];
    
    self.logInBtn = logInBtn;
    
    //接收通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nameSet) name:@"nameNote" object:nil];
    
    
    // 初始化昵称
    _nickname = self.logInBtn;
    [self addSubview:_nickname];
    
    // 初始化头像
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 20, 80, 80)];
    _imageView.layer.cornerRadius = 40; // 设置为圆形
    _imageView.layer.masksToBounds = YES; // 若不加这句话，加载的图片还是矩形的。
    [self addSubview:_imageView];
    
}
#pragma MARK - 通知方法
- (void)nameSet{
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"];
    [_nickname setTitle:str forState:UIControlStateNormal];
    NSString *url = [[NSUserDefaults standardUserDefaults]objectForKey:@"headimgurl"];
    NSLog(@"display.url = %@", url);
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
    self.imageView.image = image;

    
}
#pragma MARK - 移除通知
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"nameNote" object:nil];
    
}

#pragma MARK - logInBtn
- (void)logInBtnClick
{
    if (![_logInBtn  isEqual: @"请登录"]) {
        
        _logInBtn.enabled = NO;
        
    }
    
    LWLogInVc *logIn = [LWLogInVc new];
    
    [self.viewController presentViewController:logIn animated:YES completion:nil];
    
    
}

@end
